package com.corn.turorial.spring.controller;

import com.corn.turorial.spring.exception.MyRuntimeException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/2/1 15:21
 */
@Controller
public class MVCDebugSourceCodeController {

    @GetMapping("/test/{id}")
    @ResponseBody
    public Map test(@RequestParam("code") String code,
                    @PathVariable("id") String id,
                    @RequestHeader("User-Agent") String userAgent,
                    @RequestBody String body,
                    @CookieValue("jsessionid") String cookie,
                    ModelAndView modelAndView,
                    Model model
    ) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("id", id);
        result.put("userAgent", userAgent);
        result.put("body", body);
        result.put("cookie", cookie);
        return result;
    }

    @PostMapping("/ids")
    @ResponseBody
    public String test(@RequestBody List<Long> ids) {
        System.out.println(ids);
        return "success";
    }

    @GetMapping("/viewTest")
    public String viewTest(Model model) {
        model.addAttribute("code", 123);
        model.addAttribute("msg", "model message");
        return "view.html";
    }

    @GetMapping("/redirectTest")
    public String redirectTest() {
        return "redirect:view.html";
    }

    @ResponseBody
    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        try {
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File("E:\\java_project\\integration-project\\spring-tutorial\\src\\main\\resources\\test\\" + file.getOriginalFilename())));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "update success";
    }

    @ResponseStatus(code = HttpStatus.NOT_ACCEPTABLE, reason = "自定义异常")
    @GetMapping("/testResponseStatus")
    public String testResponseStatus() {
        int i = 1 / 0;
        throw new MyRuntimeException("my runtime exception");
//        return "error";
    }

    @ResponseBody
    @GetMapping("/testException")
    public Map<String, Object> testException() {
        int i = 1 / 0;
        return null;
    }
}
